#!/usr/bin/env python
#coding=utf-8
"""转换函数, 包括各种编码，各种进制

#decode是将其它格式转换成UniCode,encode是转成其它格式, 中文windows默认gb2312

##unicode
#>>> u'中国'
#u'\u4e2d\u56fd'

##gb2312
#>>> '中国'
#'\xd6\xd0\xb9\xfa'

##utf8
#>>> '中国'.decode('gbk').encode('utf8')
#'\xe4\xb8\xad\xe5\x9b\xbd'

"""

def hexLink(high, low):
    """16进制高位和低位相连, 即高位左移8位，然后加上低位。16进制相加结果是10进制的，所以还要转化
    >>> hexLink(0x62, 0x10)
    '0x6210'
    """
    integer = (high << 8) + low
    return hex(integer)

def charToAscii(char):
    """
    >>> charToAscii('s')
    115
    """
    return ord(char)

def asciiToChar(ascii):
    """
    >>> asciiToChar(115)
    's'
    """
    return chr(ascii)

def hexToInt(hex):
    """
    >>> hexToInt('0xff4')
    4084
    >>> hexToInt('ff4')
    4084
    """
    return int(hex, 16)

def intToHex(integer):
    """
    >>> intToHex(285)
    '0x11d'
    """
    return hex(integer)

import binascii 
def asciiToHex(str):
    """
    >>> asciiToHex('china')
    '6368696e61'
    """
    return binascii.hexlify(str)

def hexToAscii(hex):
    """
    >>> hexToAscii('6368696e61')
    'china'
    """
    return binascii.unhexlify(hex)

def crc32(str):
    """循环冗余效验
    >>> crc32('hello world')
    222957957L
    """
    return binascii.crc32(str) &0xffffffff

import base64
def base64Encode(str):
    """
    >>> base64Encode('data to be encoded')
    'ZGF0YSB0byBiZSBlbmNvZGVk\\n'
    """
    return base64.encodestring(str)

def base64Decode(str):
    """
    >>> base64Decode('ZGF0YSB0byBiZSBlbmNvZGVk')
    'data to be encoded'
    """
    return base64.decodestring(str)

def unicodeToHanzi(unicode):  
    s = "u'%s'" % unicode
    return eval(s)   

s = '\u4f60\u597d'
print eval("u'%s'" %s) == u'你好'

def unicodeToHanzi_special(s):
    return eval("u'%s'" % ''.join(['\u%s' % i[3:] for i in s.split(';')]))

s='&#x60A8;&#x7684;&#x5361;&#x69FD;&#x53EF;&#x80FD;&#x4E0D;&#x4E3A;&#x7A7A;&#xFF0C;&#x8BF7;&#x5237;&#x65B0;&#x9875;&#x9762;&#x518D;&#x8BD5;&#x3002'
print unicodeToHanzi_special(s) == u'您的卡槽可能不为空，请刷新页面再试。'

import urllib
print urllib.quote_plus(u'登录'.encode('utf-8')) == '%E7%99%BB%E5%BD%95'
print urllib.unquote_plus('%E7%99%BB%E5%BD%95') == u'登录'.encode('utf-8')

def unicode_gbk(unicode):
    """
    '\u7a7f\u8d8a'->'%b4%a9%d4%bd'
    """
    s = "u'%s'" % unicode
    s = eval(s)   
    return urllib2.quote(s.encode('gbk'))

#import lib.pyDes as pyDes
#def desEncrypt(str):
    #'''自定义可逆加密
    #>>> print desEncrypt('china')
    #\xa2Nr\xa6\x01\x95\xd3\x1f
    #'''
    #k = pyDes.des("MyDESKey")  
    #return k.encrypt(str, " ")

#def desDecrypt(str):
    #'''自定义可逆解密
    #>>> desDecrypt('\xa2Nr\xa6\x01\x95\xd3\x1f')
    #'china'
    #'''
    #k = pyDes.des("MyDESKey")  
    #return k.decrypt(str, " ")
